<?php

/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2019/7/2
 * Time: 9:16
 */

namespace app\live\controller;

use App\Http\Controllers\Controller;
use App\Http\Controllers\Live\ServerAPIController;
use think\Db;

/**
 * 直播服务，结合自己业务(未使用)
 * Class LiveService
 * @package app\live\controller
 */
class LiveServiceController extends Controller
{

    private $AppKey = '';
    private $AppSecret = '';
    public  $WyObj; //网易接口对象
    private $type = 0; //频道类型   所有频道类型均使用  rtmp(0)


    public function __construct()
    {
        parent::__construct();
        $this->AppKey = config('other.wy_app_key');
        $this->AppSecret = config('other.wy_app_secket');
        $this->WyObj = new ServerAPIController($this->AppKey, $this->AppSecret);
    }

    /**
     * 直播配置，开始直播，创建直播频道
     * @param $img   封面
     * @param $title 标题
     * @param $intro 简介
     * @param $type_id 分类id
     * @param $stadium_id 场馆id
     * @param $token   用户token
     */
    public function createChannel()
    {
        $param = $this->params;
        $result = $this->validate($param, 'app\live\validate\LiveServiceValidate.create');
        if ($result !== true) return $this->returnApi(201, $result);
        //判断用户是否具有直播权限
        $user_info = Db::name('user_info')->getByToken($param['token']);
        $is_live = Db::name('n_anchor')->where('user_id', $user_info['id'])->value('is_live');
        if ($is_live !== 1) {
            return $this->returnApi(203, '您无权直播');
        }
        // 启动事务
        Db::startTrans();
        try {
            //创建直播
            $where['title'] = $param['title'];
            $where['img']   = $param['img'];
            $where['intro'] = $param['intro'];
            $where['type_id'] = $param['type_id'];
            $where['stadium_id'] = $param['stadium_id'];
            $where['user_id'] = $user_info['id'];
            $where['node'] = 2;
            $where['live_state'] = 1;
            $where['create_time'] = date('Y-m-d H:i:s');
            $where['change_time'] = date('Y-m-d H:i:s');
            $live_id = Db::name('live_views')->insertGetId($where);
            //向网易云直播创建频道
            $name = $param['title'] . '-' . date('YmdHis'); //所有频道都加上当前时间
            $result = $this->WyObj->channelCreate($name, $this->type);
            if ($result['code'] === 200) {
                //创建成功
                //修改之前的数据
                Db::name('live_views')->update(['id' => $live_id, 'cid' => $result['ret']['cid']]);

                $data = $result['ret'];
                $data['id'] = $live_id; //本地数据库id
                // $data['requestId'] = $result['requestId'];

                //设置频道为录制状态(设置录制信息)
                $result = $this->WyObj->setChannelTranscribeInfo($result['ret']['cid'], 1, 0, 20);
                if ($result['code'] !== 200) {
                    throw new \Exception();
                }
                /* $a =  $result;
                //将数组编程字符串的样式
                $aString = '$a = '.var_export($a, true).';';
                //写入文件
                file_put_contents(__DIR__.'/a3.txt', $aString);

                $a = $data;
                //将数组编程字符串的样式
                $aString = '$a = '.var_export($a, true).';';
                //写入文件
                file_put_contents(__DIR__.'/a1.txt', $aString);*/

                // 提交事务
                Db::commit();
                return $this->returnApi(200, '创建成功', 'YES', $data);
            } else {
                throw new \Exception();
            }
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollBack();
            return $this->returnApi(202, '网络错误，请重试');
        }
    }
    /**
     * 获取直播分类
     */
    public function getLiveType()
    {
        $data = Db::name('live_type')->field("id , title")->where('is_del', 1)->select();
        if ($data) {
            return $this->returnApi(200, '获取成功', 'YES', $data);
        } else {
            return $this->returnApi(202, '暂无数据');
        }
    }

    /**
     * 获取直播类型和场馆
     * @return \think\response\Json
     */
    public function livesType()
    {
        # 总分馆
        $b[] = ["stadium_id" => "", "name" => "全部分馆"];
        $branch = Db::name("branch_info")->field("id as stadium_id,name")->order("name asc")->select();

        # 直播回看类型
        $t[] = ["type_id" => "", "title" => "全部类型"];
        $type = Db::name("live_type")->field("id as type_id,title")->where("is_del", 1)->order("title asc")->select();

        return $this->returnApi(200, "获取成功", "YES", [
            "branch" => array_merge($b, $branch), # 总分馆
            "type" => array_merge($t, $type),  # 直播会看分类
        ]);
    }

    /**
     * 获取主播是否还有未结束的直播
     * @param token  用户token
     */
    public function getLiveState()
    {
        $result = $this->validate($this->params, 'app\live\validate\LiveServiceValidate.state');
        if ($result !== true) return $this->returnApi(201, $result);
        $user_id = $this->getUserId($this->params['token']);
        $live_info = Db::name('live_views')->where(['user_id' => $user_id, 'live_state' => 1])->find();
        if ($live_info) {
            //获取推流拉流地址
            $result = $this->WyObj->channelRefreshAddr($live_info['cid']);
            if ($result['code'] === 200) {
                $data = $result['ret'];
                $data['state'] = true;
                $data['id'] = $live_info['id'];
                $data['cid'] = $live_info['cid'];
            } else {
                //获取不到的话，强制关闭频道
                Db::name('live_views')->where('id', $live_info['id'])->update(['live_state' => 2, 'end_time' => date('Y-m-d H:i:s')]);
                //禁止推流地址直播
                $this->WyObj->channelForbid($this->params['cid']);

                $data['state'] = false;
            }
        } else {
            $data['state'] = false;
        }
        return $this->returnApi(200, '获取成功', 'YES', $data);
    }

    /**
     * 结束视频直播
     * @param cid  直播视频cid
     */
    public function finishLive()
    {
        $result = $this->validate($this->params, 'app\live\validate\LiveServiceValidate.finish');
        if ($result !== true) return $this->returnApi(201, $result);
        Db::startTrans();
        try {
            Db::name('live_views')->where('cid', $this->params['cid'])->update(['live_state' => 2, 'end_time' => date('Y-m-d H:i:s')]);
            //禁止推流地址直播
            $this->WyObj->channelForbid($this->params['cid']);

            // 提交事务
            Db::commit();
            return $this->returnApi(200, '结束成功', 'YES');
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollBack();
            return $this->returnApi(202, '网络错误，请重试');
        }
    }
}
